package com.hh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.hh.oss.service.OssService;
import com.hh.oss.utils.ConstValue;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

@Service
public class OssServiceImp implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String bucketName = ConstValue.BUCKET_NAME;
        String  endPoint= ConstValue.END_POINT;
        String keyId = ConstValue.KEY_ID;
        String keySecret = ConstValue.KEY_SECRET;
        OSS ossClient = null;
        String url = "";
        try {
            InputStream fileInputStream = file.getInputStream();
            ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);

            String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + file.getOriginalFilename();
            String filePath = "head/" + new DateTime().toString("yyyy/MM/dd") + "/";
            ossClient.putObject(new PutObjectRequest(bucketName, filePath + fileName, fileInputStream));
            url = "https://" + bucketName + "." + endPoint + "/" + filePath + fileName;
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }
}
